package com.itheima.app.manager;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.itheima.app.interceptor.UserHolder;
import com.itheima.domain.db.UserInfo;
import com.itheima.domain.mongo.FocusUser;
import com.itheima.domain.mongo.Video;
import com.itheima.service.db.UserInfoService;
import com.itheima.service.mongo.FocusUserService;
import com.itheima.service.mongo.VideoService;
import com.itheima.util.ConstantUtil;
import com.itheima.vo.PageBeanVo;
import com.itheima.vo.VideoVo;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Component
public class VideoManager {

    @Reference
    private VideoService videoService;

    @Reference
    private UserInfoService userInfoService;

    @Autowired
    private FastFileStorageClient client;

    @Autowired
    private FdfsWebServer webServer;

    @Reference
    private FocusUserService focusUserService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    // 视频列表  （110_1_10、110_2_10、110_3_10）
    @Cacheable(value = "tanhua-video", key = "#userId+'_'+#pageNum +'_'+#pageSize")
    public PageBeanVo findVideoVoByPage(Long userId, Integer pageNum, Integer pageSize) {
        System.out.println(userId + "用户，查询：" + pageNum + "页");
        // 1.调用rpc查询
        PageBeanVo pageBeanVo = videoService.findVideoByPage(userId, pageNum, pageSize);

        // 2.封装vo
        List<VideoVo> voList = new ArrayList<>();
        // 2-1 取出videoList
        List<Video> videoList = (List<Video>) pageBeanVo.getItems();
        // 2-2 遍历
        if (CollectionUtil.isNotEmpty(videoList)) {
            for (Video video : videoList) {
                // 查询视频发布人的userInfo
                UserInfo userInfo = userInfoService.findByUserId(video.getUserId());

                // 创建vo
                VideoVo vo = new VideoVo();
                // 设置用户信息
                vo.setUserId(userInfo.getId());
                vo.setAvatar(userInfo.getAvatar());
                vo.setNickname(userInfo.getNickname());

                vo.setId(video.getId().toString());
                vo.setCover(video.getPicUrl());  // 视频封面
                vo.setVideoUrl(video.getVideoUrl()); // 视频连接
                vo.setSignature(video.getText()); // 视频内容
                vo.setLikeCount(video.getLikeCount()); // 点赞数量
                vo.setCommentCount(video.getCommentCount()); // 评论数量

                vo.setHasLiked(0); // 是否点赞

                if (stringRedisTemplate.hasKey(StrUtil.format(ConstantUtil.FOCUS_USER, userId, video.getUserId()))) {
                    vo.setHasFocus(1); // 关注
                } else {
                    vo.setHasFocus(0); // 未关注
                }

                // 添加到集合
                voList.add(vo);

            }
        }
        // 3.重置vo到分页对象
        pageBeanVo.setItems(voList);

        // 4.返回分页对象
        return pageBeanVo;
    }

    // 发布视频
    @CacheEvict(value = "tanhua-video",key = "#userId+'_*'")
    public void saveVideo(Long userId, MultipartFile videoThumbnail, MultipartFile videoFile) throws IOException {
        // 1.上传封面
        StorePath picPath = client.uploadFile(videoThumbnail.getInputStream(), videoThumbnail.getSize(), FileUtil.extName(videoThumbnail.getOriginalFilename()), null);
        String picUrl = webServer.getWebServerUrl() + picPath.getFullPath();
        // 2.上传视频
        StorePath videoPath = client.uploadFile(videoFile.getInputStream(), videoFile.getSize(), FileUtil.extName(videoFile.getOriginalFilename()), null);
        String videoUrl = webServer.getWebServerUrl() + videoPath.getFullPath();

        // 3.封装video对象
        Video video = new Video();
        video.setCreated(System.currentTimeMillis());  // 发布时间
        video.setUserId(userId); // 发布用户id
        video.setText("什么是快乐星球?"); // 发布心情
        video.setPicUrl(picUrl); // 视频封面
        video.setVideoUrl(videoUrl); // 视频内容

        // 4.调用rpc
        videoService.saveVideo(video);
    }

    // 关注
    public void saveFocusUser(Long focusUserId) {
        // 1.获取登录用户id
        Long userId = UserHolder.get().getId();
        // 2.封装focusUser
        FocusUser focusUser = new FocusUser();
        focusUser.setCreated(System.currentTimeMillis()); // 关注时间
        focusUser.setUserId(userId); // 用户id
        focusUser.setFocusUserId(focusUserId); // 关注用户id（视频发布用户）
        // 3.调用rpc
        focusUserService.saveFocusUser(focusUser);
        // 4.将关注标记存入redis
        stringRedisTemplate.opsForValue().set(StrUtil.format(ConstantUtil.FOCUS_USER, userId, focusUserId), "1");

    }

    // 取消关注
    public void removeFocusUser(Long focusUserId) {
        // 1.获取登录用户id
        Long userId = UserHolder.get().getId();
        // 2.调用rpc
        focusUserService.removeFocusUser(userId, focusUserId);
        // 3.将关注标记从redis移除
        stringRedisTemplate.delete(StrUtil.format(ConstantUtil.FOCUS_USER, userId, focusUserId));
    }
}
